package com.jingyanzi.member.controller;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.jingyanzi.member.api.SessionClientAPI;
import com.jingyanzi.member.domain.LeadDO;
import com.jingyanzi.member.domain.LeadLoseDO;
import com.jingyanzi.member.domain.LoginDO;
import com.jingyanzi.member.domain.result.ResultDO;
import com.jingyanzi.member.domain.result.ResultSupport;
import com.jingyanzi.member.query.LeadQueryDO;
import com.jingyanzi.member.response.PageResponse;
import com.jingyanzi.member.service.IAnalysisService;
import com.jingyanzi.member.util.MemberConstant;
import com.jingyanzi.resallocation.domain.SingleRequest;
import com.jingyanzi.resallocation.result.SingleResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(value = "业务查询controller", tags = { "业务接口" })
@RestController
@RequestMapping("/")
public class LeadController {

	public static final String SYS_ERROR = "{status:500, msg:\"系统错误\", version:1}";

	public static final String DES = "3DES";

	public static final String PLANINTEXT = "plaintext";

	@Autowired
	private IAnalysisService analysisService;

	@Autowired
	private SessionClientAPI sessionClientAPI;

	private LoginDO getLoginDO(String token) {
		Base64.Encoder encoder = Base64.getEncoder();
		LoginDO loginDO = new LoginDO();
		try {
			String t = encoder.encodeToString(token.getBytes("utf-8"));
			loginDO = sessionClientAPI.getSession(t);
			if (loginDO == null) {
				loginDO = new LoginDO();
				loginDO.setId(1);
				loginDO.setMobile("13800000000");
				loginDO.setNickname("罗于红");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return loginDO;
	}

	@ApiOperation(value = "创建业务", notes = "创建业务")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "request", value = "业务对象", required = true, dataType = "SingleRequest<LeadDO>") })
	@RequestMapping(value = "/add.json", method = RequestMethod.POST)
	public SingleResponse<LeadDO> add(@RequestBody SingleRequest<LeadDO> request) {

		LeadDO domain = request.getData();

		LoginDO loginDO = getLoginDO(request.getToken());
		domain.setAuthorId(loginDO.getId());
		domain.setAuthor(loginDO.getNickname());
		domain.setCollectorEmployeeID(loginDO.getId());
		domain.setCollectorEmployeeName(loginDO.getNickname());

		ResultDO result = analysisService.add(domain);
		SingleResponse<LeadDO> response = new SingleResponse<LeadDO>();
		if (result.isSuccess()) {
			response.setStatus(200);
			response.setVersion(1);
			response.setMsg("添加成功");
		} else {
			response.setStatus(500);
			response.setVersion(1);
			response.setMsg("添加失败");
		}
		return response;
	}

	@ApiOperation(value = "修改业务信息", notes = "修改业务信息 修改业务信息要传入 业务的 id")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "request", value = "业务对象", required = true, dataType = "SingleRequest<LeadDO>") })
	@RequestMapping(value = "/edit.json", method = RequestMethod.POST)
	public SingleResponse<LeadDO> edit(@RequestBody SingleRequest<LeadDO> request) {

		LeadDO domain = request.getData();

		domain.setModifiId(getLoginDO(request.getToken()).getId());
		domain.setModifiTimeName(getLoginDO(request.getToken()).getNickname());

		ResultDO result = analysisService.edit(domain);
		SingleResponse<LeadDO> response = new SingleResponse<LeadDO>();
		if (result.isSuccess()) {
			response.setStatus(200);
			response.setVersion(1);
			response.setMsg("修改成功");
		} else {
			response.setStatus(500);
			response.setVersion(1);
			response.setMsg("修改失败");
		}
		return response;
	}

	@ApiOperation(value = "获取业务详情", notes = "获取业务详情只用传业务的 id")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "request", value = "业务对象(只传业务ID)", required = true, dataType = "SingleRequest<CustomerFamilyDO>") })
	@RequestMapping(value = "/detail.json", method = RequestMethod.POST)
	public SingleResponse<LeadDO> detail(@RequestBody SingleRequest<LeadDO> request) {

		LeadDO domain = request.getData();

		ResultDO result = analysisService.get(domain.getId());
		SingleResponse<LeadDO> response = new SingleResponse<LeadDO>();
		if (result.isSuccess()) {
			response.setStatus(200);
			response.setVersion(1);
			response.setMsg("获取成功");
			response.setData((LeadDO) result.getModel(ResultSupport.FIRST_MODEL_KEY));
		} else {
			response.setStatus(500);
			response.setVersion(1);
			response.setMsg("获取失败");
		}
		return response;
	}

	@ApiOperation(value = "删除业务信息", notes = "删除业务信息只传入业务的ID")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "request", value = "业务对象(业务ID)", required = true, dataType = "SingleRequest<CustomerFamilyDO>") })
	@RequestMapping(value = "/delete.json", method = RequestMethod.POST)
	public SingleResponse<LeadDO> delete(@RequestBody SingleRequest<LeadDO> request) {

		LeadDO domain = request.getData();

		ResultDO result = analysisService.remove(domain.getIds());
		SingleResponse<LeadDO> response = new SingleResponse<LeadDO>();
		if (result.isSuccess()) {
			response.setStatus(200);
			response.setVersion(1);
			response.setMsg("删除成功");
		} else {
			response.setStatus(500);
			response.setVersion(1);
			response.setMsg("删除失败");
		}
		return response;
	}

	@ApiOperation(value = "业务流失", notes = "业务流失修改业务状态添加流失信息创建流失业务对象")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "request", value = "业务流失DO", required = true, dataType = "SingleRequest<LeadLostDO>") })
	@RequestMapping(value = "/lose.json", method = RequestMethod.POST)
	public SingleResponse<LeadLoseDO> lose(@RequestBody SingleRequest<LeadLoseDO> request) {

		LeadLoseDO domain = request.getData();

		LoginDO loginDO = getLoginDO(request.getToken());
		domain.setSaleEmployeeID(loginDO.getId());

		ResultDO result = analysisService.lose(domain);
		SingleResponse<LeadLoseDO> response = new SingleResponse<LeadLoseDO>();
		if (result.isSuccess()) {
			response.setStatus(200);
			response.setVersion(1);
			response.setMsg("删除成功");
		} else {
			response.setStatus(500);
			response.setVersion(1);
			response.setMsg("删除失败");
		}
		return response;
	}

	@ApiOperation(value = "自动分配", notes = "自动分配业务给指点的销售")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "request", value = "业务查询DO，传入上次的查询条件", required = true, dataType = "SingleRequest<LeadDO>") })
	@RequestMapping(value = "/autoAllocation.json", method = RequestMethod.POST)
	public SingleResponse<LeadDO> autoAllocation(HttpServletRequest req, @RequestBody SingleRequest<LeadDO> request) {

		LeadDO domain = request.getData();
		LoginDO loginDO = getLoginDO(request.getToken());

		HttpSession session = req.getSession();
		LeadQueryDO query = (LeadQueryDO) session.getAttribute("LEAD_QUERY_DO" + loginDO.getId());
		query.setPage(false);
		ResultDO result = analysisService.autoAllocation(query, loginDO.getId(), loginDO.getNickname());

		SingleResponse<LeadDO> response = new SingleResponse<LeadDO>();
		if (result.isSuccess()) {
			response.setStatus(200);
			response.setVersion(1);
			response.setMsg("删除成功");
		} else {
			response.setStatus(500);
			response.setVersion(1);
			response.setMsg("删除失败");
		}
		return response;
	}

	@ApiOperation(value = "业务找回", notes = "业务流失后业务找回")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "request", value = "业务对象", required = true, dataType = "SingleRequest<LeadDO>") })
	@RequestMapping(value = "/recover.json", method = RequestMethod.POST)
	public SingleResponse<LeadDO> recover(@RequestBody SingleRequest<LeadDO> request) {

		LeadDO domain = request.getData();
		domain.setStatus(MemberConstant.LEAD_STATUS_TRACKINT); // 跟进中
		ResultDO result = analysisService.loseBack(domain);
		SingleResponse<LeadDO> response = new SingleResponse<LeadDO>();
		if (result.isSuccess()) {
			response.setStatus(200);
			response.setVersion(1);
			response.setMsg("删除成功");
		} else {
			response.setStatus(500);
			response.setVersion(1);
			response.setMsg("删除失败");
		}
		return response;
	}

	@ApiOperation(value = "业务委托", notes = "业务委托")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "request", value = "业务DO", required = true, dataType = "SingleRequest<LeadDO>") })
	@RequestMapping(value = "/entrust.json", method = RequestMethod.POST)
	public SingleResponse<LeadDO> entrust(@RequestBody SingleRequest<LeadDO> request) {

		LeadDO domain = request.getData();

		ResultDO result = analysisService.modifi(domain);
		SingleResponse<LeadDO> response = new SingleResponse<LeadDO>();
		if (result.isSuccess()) {
			response.setStatus(200);
			response.setVersion(1);
			response.setMsg("删除成功");
		} else {
			response.setStatus(500);
			response.setVersion(1);
			response.setMsg("删除失败");
		}
		return response;
	}

	@ApiOperation(value = "分配销售", notes = "业务分配销售")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "request", value = "分配销售DO", required = true, dataType = "SingleRequest<LeadDO>") })
	@RequestMapping(value = "/allocation.json", method = RequestMethod.POST)
	public SingleResponse<LeadDO> allocation(@RequestBody SingleRequest<LeadDO> request) {

		LeadDO domain = request.getData();
		LoginDO loginDO = getLoginDO(request.getToken());
		domain.setAlloEmployeeID(loginDO.getId());
		domain.setAlloEmployeeName(loginDO.getNickname());

		ResultDO result = analysisService.allocation(domain);

		SingleResponse<LeadDO> response = new SingleResponse<LeadDO>();
		if (result.isSuccess()) {
			response.setStatus(200);
			response.setVersion(1);
			response.setMsg("删除成功");
		} else {
			response.setStatus(500);
			response.setVersion(1);
			response.setMsg("删除失败");
		}
		return response;
	}

	@ApiOperation(value = "查询业务信息", notes = "查询业务信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "request", value = "查询查询对象", required = true, dataType = "SingleRequest<LeadQueryDO>") })
	@RequestMapping(value = "/query.json", method = RequestMethod.POST)
	public PageResponse<LeadDO> query(HttpServletRequest req, @RequestBody SingleRequest<LeadQueryDO> request) {

		// 未分配业务：status = 1; 业务跟踪: status默认不传 或根据查询条件； 流失业务: status = 8
		LeadQueryDO query = request.getData();

		if (query.getPageRows() > 0) {
			query.setPage(true);
		}
		LoginDO loginDO = getLoginDO(request.getToken());
		ResultDO result = analysisService.query(query);
		HttpSession session = req.getSession();
		session.setAttribute("LEAD_QUERY_DO" + loginDO.getId(), query);
		PageResponse<LeadDO> response = new PageResponse<LeadDO>();

		if (result.isSuccess()) {
			response.setStatus(200);
			response.setVersion(1);
			response.setMsg("查询成功");
			response.setData((List<LeadDO>) result.getModel(ResultSupport.FIRST_MODEL_KEY));
			if (query.isPage()) {
				response.setPageindex(query.getPageNO());
				response.setPagesize(query.getPageRows());
				response.setTotal((Long) result.getModel(ResultSupport.SECOND_MODEL_KEY));
			}
		} else {
			response.setStatus(500);
			response.setVersion(1);
			response.setMsg("查询失败");
		}
		return response;
	}

}
